using UnityEngine;

public class ParticleCollector_ForceField : MonoBehaviour
{
    private ParticleSystem _particleSystem;
    private ParticleSystem.Particle[] _particles;

    [SerializeField] private Transform _Target;
    [SerializeField] private ParticleSystemForceField _ForceField;

    [SerializeField] private float _DestroyThreshold = 0.3f;

    private void Awake()
    {
        if (_particleSystem == null)
        {
            _particleSystem = GetComponentInChildren<ParticleSystem>();
            _particles = new ParticleSystem.Particle[_particleSystem.main.maxParticles];
        }

        if (_ForceField == null)
        {
            _ForceField = GetComponentInChildren<ParticleSystemForceField>();
        }

        FollowTarget();
    }

    private void OnEnable()
    {
        _particleSystem.Play(true);
    }

    private void Update()
    {
        if (_particleSystem == null || _ForceField == null || _Target == null)
        {
            return;
        }

        FollowTarget();

        CheckParticles();
    }

    private void CheckParticles()
    {
        var targetPos = _Target.position;
        var particleCount = _particleSystem.GetParticles(_particles);
        for (int i = 0; i < particleCount; ++i)
        {
            var curPos = _particles[i].position;

            var dist = Vector3.Distance(curPos, targetPos);
            if (dist < _DestroyThreshold)
            {
                _particles[i].remainingLifetime = -1;
            }
        }

        _particleSystem.SetParticles(_particles, particleCount);
    }

    private void FollowTarget()
    {
        if (_ForceField == null || _Target == null)
        {
            return;
        }

        _ForceField.transform.position = _Target.position;
    }

    public void SetTarget(Transform target)
    {
        _Target = target;
    }
}
